package utils;

import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

@SuppressWarnings("All")
public class JDBCUtil {
    private static String url;
    private static String user;
    private static String password;
    private static Connection con;
    private static String driver;

    /**
     * 静态代码块，自动执行，只执行一次
     */
    static {
        //创建Properties类的对象
        Properties properties = new Properties();
        //类加载器
        ClassLoader classLoader = JDBCUtil.class.getClassLoader();
        //获得src目录下的jdbc.properties文件目录，返回是URL类型
        URL resource = classLoader.getResource("jdbc.properties");
        //得到文件路径，String类型
        String path = resource.getPath();
        System.out.println(path);
        try {
            //加载文件
            properties.load(new FileReader(path));
            //文件获取相应的值
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            driver = properties.getProperty("driver");
            Class.forName(driver);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnect() {
        try {
            con = DriverManager.getConnection(url, user, password);
            System.out.println("数据库连接成功");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return con;
    }

    public static void close(Statement st, ResultSet re, Connection con) {
        if (st != null) {
            try {
                st.close();
                System.out.println("Statement关闭");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        } else if (re != null) {
            try {
                re.close();
                System.out.println("ResultSet关闭");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        } else if (con != null) {
            try {
                con.close();
                System.out.println("Connection关闭");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        getConnect();
    }

}


